﻿using GComp.Apps.EasyStock.Data;
using GComp.Apps.EasyStock.DataModel.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace GComp.Apps.EasyStock.DataModel {
    public class DataContext {
        #region Constructor and instance

        private DataContext() {
        }

        private static DataContext instance;
        public static DataContext Instance { get { return instance ?? (instance = new DataContext()); } }

        #endregion //Constructor and instance

        private DataManager manager;
        private SampleDataSource data;

        public DataManager DataManager { get { return manager; } }
        public SampleDataSource UIData { get { return data; } }

        public bool IsInitialized { get; private set; }

        public async void SetUp() {
            manager = DataManager.Instance;
            data = SampleDataSource.Instance;
            await manager.SetUp();
            InitDataSource();

            IsInitialized = true;
        }

        public void InitDataSource() {
            data.AllGroups.Clear();

            foreach (StockGroup group in manager.Groups) {
                SampleDataGroup dataGroup = CreateFromDataGroup(group);

                foreach (StockEntry entry in group.Entries) {
                    dataGroup.Items.Add(CreateItemFromEntry(dataGroup, entry));
                }
                data.AllGroups.Add(dataGroup);
            }

            //add group add
            SampleDataGroup addGroup = new SampleDataGroup(Keys.Common.Add, "Add", "Add a new group to the collection", "Assets/AddNew3.png", "Add a new group");
            data.AllGroups.Add(addGroup);
        }

        public static SampleDataItem CreateItemFromEntry(SampleDataGroup dataGroup, StockEntry entry) {
            return new SampleDataItem(entry.Id, entry.Name, entry.Description, "Assets/LightGray.png", entry.Symbol, entry.Symbol, dataGroup);
        }

        public static SampleDataGroup CreateFromDataGroup(StockGroup group) {
            return new SampleDataGroup(group.Id, group.Name, group.Description, "Assets/IconBackground.png", "content");
        }

        internal async Task<DataManager> TearDown() {
            return await DataManager.TearDown();
        }
    }
}
